//
//  CXLPhotoBrowserViewCell.swift
//  weibo1990
//
//  Created by 曹晓龙 on 15/10/26.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit
import SDWebImage

///  点击Cell的代理方法
protocol CXLPhotoBrowserCellDelegate:NSObjectProtocol{
    
    ///  点击图片,关闭图片浏览
    func photoBrowserCellClickDismissPicture()
    
    ///  图片缩放的比例
    func photoBrowserCellPictureScale(scale:CGFloat)
}

/// 查看图片Cell
class CXLPhotoBrowserViewCell: UICollectionViewCell {
    
    /// 代理属性
    weak var photoCellDelegate:CXLPhotoBrowserCellDelegate?
    
    //MARK: - 监听方法
    ///  点击图片,关闭弹出视图
    @objc private func clickPicture(){
        
        photoCellDelegate?.photoBrowserCellClickDismissPicture()
    }
    
    //:MARK: -传入的url
    var url:NSURL? {
        
        didSet{
           
            guard let url = url else{
                return
            }
            regizerScrollViewOffset()
            
            setHolderImgView(url)
            
            let bmiddleUrl = getBmiddleURL(url)
            
            imgView.sd_setImageWithURL(bmiddleUrl,
                placeholderImage: nil,
                options: [SDWebImageOptions.RetryFailed, SDWebImageOptions.RefreshCached],
                progress: { (current, total) -> Void in
                    
                    let progress:CGFloat = CGFloat(current) / CGFloat(total)
                    
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        
                        self.holderImgView.progress = progress
                    })
                    
                    
                }) { (image, _, _, _) -> Void in
                    
                    self.holderImgView.hidden = true
                    
                    if image != nil {
                        
                        self.setImgViewPosition(image)
                    }
            }
        }
    }
    
    ///  设置站位图片
    ///
    ///  - parameter url: guard 判断后的url
    private func setHolderImgView(url:NSURL){
        
        holderImgView.hidden = false
        
        holderImgView.sd_setImageWithURL(url)
        
        holderImgView.sizeToFit()
        
        holderImgView.center = scrollView.center
    }
    
    
    ///  清空所有scrollView 的content属性,
    private func regizerScrollViewOffset(){
        
        // 清空所有的transform
        scrollView.transform = CGAffineTransformIdentity
        
        // 清空所有的偏移,内边距,缩放
        scrollView.contentInset = UIEdgeInsetsZero
        
        scrollView.contentOffset = CGPointZero
        
        scrollView.contentSize = CGSizeZero
    }
    
    ///  设置图片的位置
    ///
    ///  - parameter image: 加载的中等大图
    private func setImgViewPosition(image:UIImage){
        
        let width = scrollView.bounds.width
        
        let height = image.size.height * width / image.size.width
        
        let size = CGSize(width: width, height: height)
        
        if size.height > scrollView.bounds.height {
            
            imgView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            
            scrollView.contentSize = size
            return
        }
        
        let y :CGFloat = (scrollView.bounds.height - size.height) * 0.5

        imgView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        
        scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        
    }
    
    ///  获取图片URL中等
    ///
    ///  - parameter url: 传入的url
    ///
    ///  - returns: 中等图片的URL
    private func getBmiddleURL(url:NSURL) ->NSURL{

        var urlString = url.absoluteString
        
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        
        return NSURL(string: urlString)!
        
    }
    
    //MARK: -构造函数
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 设置UI
    private func setupUI(){
    
        contentView.addSubview(scrollView)
        scrollView.addSubview(imgView)
        
        scrollView.addSubview(holderImgView)
        
        // 设置布局
        
        var rect = contentView.bounds
        
        rect.size.width -= 20
        
        scrollView.frame = rect
        
        scrollView.delegate = self
        
        scrollView.maximumZoomScale = 2.0
        
        scrollView.minimumZoomScale = 0.5
        
        scrollView.showsHorizontalScrollIndicator = false
        
        scrollView.showsVerticalScrollIndicator = false
        
        // 添加点击手势
        
        let tap = UITapGestureRecognizer(target: self, action: "clickPicture")
        
        imgView.addGestureRecognizer(tap)
        
        imgView.userInteractionEnabled = true
    }
    
    //MARK: -懒加载控键
    /// scrollView
    lazy var scrollView:UIScrollView = UIScrollView()
    /// 显示图片
    lazy var imgView:UIImageView = UIImageView()
    
    /// 站位图片
    private lazy var holderImgView:CXLProgressImageView = CXLProgressImageView()
}

// MARK: - UIScrollViewDelegate
extension CXLPhotoBrowserViewCell: UIScrollViewDelegate{
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        
        return imgView
    }
    
    ///  停止缩放
    ///  bounds 不变. 变得时 transform  frame = center + bounds * transform
    ///  - parameter scrollView: scrollView
    ///  - parameter view:       缩放的视图-- imgView
    ///  - parameter scale:      缩放的比例
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        // 停止缩放时,缩放比例小于1, 关闭图片浏览
        if scale < 1 {
            
            photoCellDelegate?.photoBrowserCellClickDismissPicture()
            
            return
        }
        
        var offsetY = (scrollView.bounds.height - (view?.frame.height)!) * 0.5
        
        offsetY = offsetY < 0 ? 0 : offsetY
        
        var offsetX = (scrollView.bounds.width - (view?.frame.width)!) * 0.5
        
        offsetX = offsetX < 0 ? 0 : offsetX
        
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        
        
    }
    
    func scrollViewDidZoom(scrollView: UIScrollView) {
        
        photoCellDelegate?.photoBrowserCellPictureScale(imgView.transform.a)
        
    }
}
